const express = require('express');
const { query } = require('../config/database-sqlite');
const { optionalAuth, authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取歌曲列表
router.get('/', optionalAuth, async (req, res) => {
  try {
    const { page = 1, limit = 20, artist_id, album_id, keyword } = req.query;
    const offset = (page - 1) * limit;

    let sql = `
      SELECT s.*, a.name as artist_name, al.name as album_name
      FROM songs s
      LEFT JOIN artists a ON s.artist_id = a.id
      LEFT JOIN albums al ON s.album_id = al.id
      WHERE s.status = 1
    `;
    const params = [];

    if (artist_id) {
      sql += ' AND s.artist_id = ?';
      params.push(artist_id);
    }

    if (album_id) {
      sql += ' AND s.album_id = ?';
      params.push(album_id);
    }

    if (keyword) {
      sql += ' AND (s.name LIKE ? OR a.name LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`);
    }

    sql += ' ORDER BY s.play_count DESC, s.created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));

    const songs = await query(sql, params);

    // 如果用户已登录，检查收藏状态
    if (req.user) {
      const songIds = songs.map(song => song.id);
      if (songIds.length > 0) {
        const placeholders = songIds.map(() => '?').join(',');
        const favorites = await query(
          `SELECT song_id FROM user_favorites WHERE user_id = ? AND song_id IN (${placeholders})`,
          [req.user.id, ...songIds]
        );
        const favoriteIds = new Set(favorites.map(f => f.song_id));
        
        songs.forEach(song => {
          song.is_favorited = favoriteIds.has(song.id);
        });
      }
    }

    res.json({
      songs,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        hasMore: songs.length === parseInt(limit)
      }
    });

  } catch (error) {
    console.error('获取歌曲列表错误:', error);
    res.status(500).json({ error: '获取歌曲列表失败' });
  }
});

// 获取歌曲详情
router.get('/:id', optionalAuth, async (req, res) => {
  try {
    const { id } = req.params;

    const songs = await query(`
      SELECT s.*, a.name as artist_name, al.name as album_name
      FROM songs s
      LEFT JOIN artists a ON s.artist_id = a.id
      LEFT JOIN albums al ON s.album_id = al.id
      WHERE s.id = ? AND s.status = 1
    `, [id]);

    if (songs.length === 0) {
      return res.status(404).json({ error: '歌曲不存在' });
    }

    const song = songs[0];

    // 检查收藏状态
    if (req.user) {
      const favorites = await query(
        'SELECT id FROM user_favorites WHERE user_id = ? AND song_id = ?',
        [req.user.id, id]
      );
      song.is_favorited = favorites.length > 0;
    }

    res.json({ song });

  } catch (error) {
    console.error('获取歌曲详情错误:', error);
    res.status(500).json({ error: '获取歌曲详情失败' });
  }
});

// 获取歌曲播放URL
router.get('/:id/url', async (req, res) => {
  try {
    const { id } = req.params;
    const { quality = 1 } = req.query;

    const songs = await query(
      'SELECT file_url FROM songs WHERE id = ? AND status = 1',
      [id]
    );

    if (songs.length === 0) {
      return res.status(404).json({ error: '歌曲不存在' });
    }

    // 这里可以根据quality参数返回不同品质的URL
    // 目前返回默认URL
    res.json({ 
      url: songs[0].file_url || `/assets/audio/default.mp3`,
      quality: parseInt(quality)
    });

  } catch (error) {
    console.error('获取播放URL错误:', error);
    res.status(500).json({ error: '获取播放URL失败' });
  }
});

// 记录播放历史
router.post('/:id/play', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { duration = 0, device_type = 'miniprogram' } = req.body;

    // 检查歌曲是否存在
    const songs = await query(
      'SELECT id FROM songs WHERE id = ? AND status = 1',
      [id]
    );

    if (songs.length === 0) {
      return res.status(404).json({ error: '歌曲不存在' });
    }

    // 记录播放历史
    await query(`
      INSERT INTO play_history (user_id, song_id, play_duration, device_type)
      VALUES (?, ?, ?, ?)
    `, [req.user.id, id, duration, device_type]);

    // 增加歌曲播放次数
    await query(
      'UPDATE songs SET play_count = play_count + 1 WHERE id = ?',
      [id]
    );

    res.json({ message: '播放记录成功' });

  } catch (error) {
    console.error('记录播放历史错误:', error);
    res.status(500).json({ error: '记录播放历史失败' });
  }
});

module.exports = router;